<template>
  <div class="edit-temp">
    <div class="return">
      <span @click="returnPage" class="icon">
        <i class="MC_iconfont MC_icon-fangxiang-zuo-xian"></i>
        动态表单
      </span>
      <span class="line">｜</span>
      <span class="tip">编辑模版</span>
    </div>
    <div class="title">模版信息设置</div>
    <el-form :model="form" :rules="rules" label-position="top" ref="formRef">
      <el-form-item label="模版名称" prop="name">
        <el-input
          style="width: 540px"
          v-model.trim="form.name"
          maxlength="20"
          show-word-limit
          placeholder="请输入模版名称，不超过20个字符"
        ></el-input>
      </el-form-item>
      <el-form-item label="模版描述" prop="description">
        <el-input
          style="width: 540px"
          type="textarea"
          v-model.trim="form.description"
          maxlength="200"
          show-word-limit
          rows="3"
          placeholder="请输入模版描述，不超过200个字符"
        ></el-input>
      </el-form-item>
      <el-form-item label="模版状态" prop="status" class="status-right">
        <el-switch v-model="form.status" />
      </el-form-item>
    </el-form>
    <div class="title">模版字段设置</div>
    <div class="add-btn" @click="addField">
      <i class="MC_iconfont MC_icon-tianjia-xian"></i>
      添加字段
    </div>
    <resize-table :headers="tableHeaders" :data="tableData" :showPagination="false" class="table" height="300">
      <template #required="{ scope }">
        <span>{{ scope.row.required ? '是' : '否' }}</span>
      </template>
      <template #status="{ scope }">
        <el-switch
          v-model="scope.row.status"
          :active-value="1"
          :inactive-value="0"
          @change="changeStatus(scope.row, scope.$index)"
          inline-prompt
        />
      </template>
      <template #sort="{ scope }">
        <span
          v-if="scope.$index !== 0"
          class="MC_iconfont MC_icon-zhi-zhiding"
          @click="toTop(scope.$index, scope.row)"
        ></span>
        <span
          v-if="scope.$index !== 0"
          class="MC_iconfont MC_icon-a-jiantou-shang-line"
          @click="moveUp(scope.$index, scope.row)"
        ></span>
        <span
          v-if="scope.$index !== tableData.length - 1"
          class="MC_iconfont MC_icon-a-jiantou-xia-line"
          @click="moveDown(scope.$index, scope.row)"
        ></span>
      </template>
      <template #oprate="{ scope }">
        <span class="btn" @click="editField(scope.row)">编辑</span>
        <span class="btn" v-if="!scope.row.builtin" @click="delField(scope.row, scope.$index)">删除</span>
      </template>
    </resize-table>
    <div class="operate-btn">
      <el-button link @click="returnPage">取消</el-button>
      <el-button type="primary" @click="saveTemp">保存</el-button>
    </div>
    <add-temp-field ref="addTempField" @onSaveData="updatTable" :tableData="tableData"></add-temp-field>
  </div>
</template>

<script lang="ts">
import { defineComponent, getCurrentInstance, reactive, toRefs, onMounted, computed, markRaw } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import resizeTable from '@/common/components/resize-table/index.vue'
import addTempField from './add-field.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { updateTemplate, detailTemplate } from '@app/base/apis/dynamic-form'
import { typeAllMap } from '@app/base/views/account/components/global-field/type'
import { commonStore } from '@/common/store/modules/common'
import mcCache from '@/common/utils/mc-get-cache'
import deleteIcon from '@/common/components/delete-icon/index.vue'
interface State {
  form: Record<string, unknown>
  rules: Record<string, unknown>
  tableHeaders: Record<string, unknown>[]
  tableData: any
  init: boolean
}
export default defineComponent({
  name: 'EditTemp',
  components: { resizeTable, addTempField },
  setup() {
    const $router = useRouter()
    const route = useRoute()
    const instance: any = getCurrentInstance()

    const state: State = reactive({
      form: {
        status: true
      },
      rules: {
        name: [{ required: true, message: '请输入模版名称', trigger: 'blur' }]
      },
      tableHeaders: [
        { label: '字段名称', prop: 'name', show: true },
        { label: '字段类型', prop: 'type', show: true },
        { label: '是否必填', prop: 'required', show: true, custom: true },
        { label: '当前状态', prop: 'status', show: true, custom: true },
        { label: '排序', prop: 'sort', show: true, custom: true },
        { label: '操作', prop: 'oprate', show: true }
      ],
      tableData: [],
      init: true
    })

    const changeStatus = (row: any, index: number) => {
      if (state.init) {
        state.init = false
        return
      }
      ElMessageBox.confirm(`请确认是否${row.status ? '启用' : '停用'}该字段？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          state.tableData[index].status = row.status
        })
        .catch(() => {
          state.tableData[index].status = row.status ? 0 : 1
        })
    }

    const returnPage = () => {
      $router.push('/account/dynamic_form')
    }

    const addField = () => {
      instance?.refs.addTempField.openDialog('add', {})
    }

    const editField = (row: any) => {
      instance?.refs.addTempField.openDialog('edit', row)
    }

    const delField = (row: any, idx: number) => {
      ElMessageBox.confirm(`${row.name}字段删除后将无法恢复，点击确定删除字段`, '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(deleteIcon)
      }).then(() => {
        state.tableData.splice(idx, 1)
      })
    }

    const updatTable = (data: any, type: string) => {
      const fieldObj: any = getFields(data.field)
      const obj = {
        ...data,
        name: fieldObj.name,
        type: fieldObj.type
      }
      if (type === 'add') {
        // 新建的字段
        state.tableData.push(obj)
      } else {
        // 编辑字段
        state.tableData.forEach((item: any, idx: number) => {
          if (item.field === data.field) {
            state.tableData[idx] = obj
          }
        })
      }
    }

    const saveTemp = () => {
      if (!state.tableData.filter((item: any) => item.status).length) {
        ElMessage.error('模版字段至少有一个启用的')
        return
      }
      const { name, status, description } = state.form
      const sendData = {
        description,
        name,
        status: status ? 1 : 0,
        fields: state.tableData,
        _id: route.query.id
      }
      instance?.refs.formRef.validate((valid: boolean) => {
        if (valid) {
          updateTemplate(sendData).then((res) => {
            if (res.success) {
              ElMessage.success('操作成功')
              // 更新pinia
              sendData.fields = sendData.fields.map((v: any) => {
                return {
                  field: v.field,
                  status: v.status,
                  required: v.required
                }
              })
              mcCache.$updateCache('dyForm', res.data, '_id', '')
              returnPage()
            }
          })
        }
      })
    }

    const globalFieldsObj: any = computed(() => {
      return commonStore().publicCache.globalFieldCacheObj || {}
    })

    // 获取字段名称、类型
    const getFields = (field: any) => {
      const data = globalFieldsObj.value[field]
      if (data) {
        return {
          name: data.name || '',
          type: typeAllMap[data.type] || ''
        }
      }
      return {}
    }

    const getDetailData = () => {
      detailTemplate({ _id: route.query.id }).then((res) => {
        if (res.success && res.data) {
          state.form.name = res.data.name
          state.form.description = res.data.description
          state.form.status = Boolean(res.data.status)
          res.data.fields.forEach((item: any) => {
            // 字段数据匹配
            const fieldObj: any = getFields(item.field)
            item.name = fieldObj.name
            item.type = fieldObj.type
          })
          state.tableData = res.data.fields
        }
      })
    }

    const toTop = (index: number, row: any) => {
      // 置顶
      state.tableData.splice(index, 1)
      state.tableData.unshift(row)
    }

    const moveUp = (index: number, row: any) => {
      // 上移
      state.tableData[index] = state.tableData.splice(index - 1, 1, row)[0]
    }

    const moveDown = (index: number, row: any) => {
      // 下移
      state.tableData[index] = state.tableData.splice(index + 1, 1, row)[0]
    }

    onMounted(async () => {
      await mcCache.$getCache('globalFieldCache', 'hasObj', '', '', '', '', 'field') // 全局字段(单独页面需在获取一次)
      getDetailData()
    })

    return {
      ...toRefs(state),
      returnPage,
      addField,
      editField,
      delField,
      saveTemp,
      toTop,
      moveUp,
      moveDown,
      updatTable,
      changeStatus
    }
  }
})
</script>

<style lang="stylus" scoped>
.resize-table
  position static !important
  height auto !important
.edit-temp
  padding 24px 24px 84px
  height calc(100vh - 60px)
  box-sizing border-box
  position relative
  overflow auto
  .return
    .icon
      cursor pointer
      .MC_icon-fangxiang-zuo-xian
        color rgba(0, 0, 0, 0.6)
        font-size 18px
        position relative
        top 2px
    .line
      color #DCDCDC
      margin 0 8px
    .tip
      color rgba(0, 0, 0, 0.6)
  .title
    height 36px
    padding 0 20px
    line-height 36px
    box-sizing border-box
    background rgba(30, 99, 245, 0.1)
    border-radius 4px
    font-size 14px
    color rgba(0, 0, 0, 0.88)
    font-weight 500
    margin 16px 0
  .status-right
    display flex
    align-items center
    :deep(.el-form-item__label)
      margin-bottom 0
  .add-btn
    float right
    color var(--mc-main-color)
    cursor pointer
    margin-bottom 16px
  .btn
    color var(--mc-main-color)
    cursor pointer
    margin-right 16px
    &:last-child
      margin-right 0px
  .operate-btn
    background #fff
    z-index 3
    position fixed
    bottom 0
    left 240px
    right 0
    height 60px
    padding 12px 24px
    box-sizing border-box
    text-align right
    border-top 1px solid var(--mc-gray3-color)
  .table
    .MC_iconfont
      color var(--mc-main-color)
      margin-right 10px
      &:last-child
        margin-right 0
</style>
